package com.hunttown.mes.common.utils;

/**
 * 数据库连接生成工具
 * created by wangjunfu on 2019-10-25
 */
public class DatabaseUtils {

    // 加密
    public static String getEncryKey(String srcStr) {
        String encKey = DesUtils.encrypt(srcStr);
        encKey = setPositionEnc(encKey);
        encKey = DesUtils.encrypt(srcStr);
        return encKey;
    }

    // 解密
    public static String getDecryKey(String decStr) throws Exception {
        String decKey = DesUtils.decrypt(decStr);
        decKey = getPositionDec(decKey);
        decKey = DesUtils.decrypt(decStr);
        return decKey;
    }

    // 将字符串偶数位和奇数位分开后再连接
    private static String setPositionEnc(String srcStr) {
        char[] srcArr = srcStr.toCharArray();
        StringBuilder preSrc = new StringBuilder();
        StringBuilder nextSrc = new StringBuilder();

        for (int i = 0; i < srcStr.length(); i++) {
            if (i % 2 == 0) {
                preSrc.append(srcArr[i]);
            } else {
                nextSrc.append(srcArr[i]);
            }
        }

        return preSrc.append(nextSrc).toString();
    }

    // 恢复字符串的奇偶数拆分
    private static String getPositionDec(String encStr) {
        Integer len = encStr.length();
        Integer preLen = len / 2 + len % 2;
        Integer nextLen = len - preLen;

        String preStr = encStr.substring(0, preLen);
        String nextStr = encStr.substring(preLen);

        char[] preArr = preStr.toCharArray();
        char[] nextArr = nextStr.toCharArray();

        StringBuilder srcStr = new StringBuilder();

        for (int i = 0; i < preLen; i++) {
            srcStr.append(preArr[i]);

            if (i < nextLen) {
                srcStr.append(nextArr[i]);
            }
        }

        return srcStr.toString();
    }

    public static void main(String[] args) throws Exception {
        String src = "6E5EB9CA4CA8F862BDDB712072D0BDA7C3E69BDAF8A13805B71338F3BD4E3A5037290691E76171F5A1F39EA5BF922ADF2F905B38BC7D9811B79CABC56EBF9A5CCC6B192B26A4D0CE9987A3C430D7EAE17B7503B18CD6522D38FB82AE5A84CEACCC0CD6972CA7EBFC9E42B973E7744FA5BE08D701830F37FAF4DACAC01A61D9D73F269AFCEF91277D";
        String mysql = "jdbc:mysql://192.168.1.234:3306/refactor_transport_analysis_history?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";

        //String enc = setPositionEnc(src);
        //System.out.println(enc);
        //System.out.println(getPositionDec(enc));

        System.out.println(mysql);
        String dec = getEncryKey(mysql);
        System.out.println(dec);
        System.out.println(getDecryKey(dec));

        //System.out.println(5 / 2 + 5 % 2);
        //System.out.println(6 / 2 + 6 % 2);

        //System.out.println("1234567".substring(0, 4));
        //System.out.println("1234567".substring(4));
    }
}
